<template>
  <el-cascader
    v-model="selectRegionCode"
    :options="regionTree"
    :props="regionProps"
    clearable
    :placeholder="regionLoading ? '区域数据加载中' : '请选择区域'"
    class="w-100%"
    @change="onRegionChange"
  />
</template>
<script lang="ts" setup>
import {oneOfType} from 'vue-types'
import {propTypes} from '@/utils/propTypes'
import {getRegionTree} from '@/api/universal/region'

/** 区域选择组件 */
defineOptions({name: 'RegionPicker'})

const props = defineProps({
  modelValue: oneOfType<number | number[] | string | string[]>([
    Number,
    Array<Number>,
    String,
    Array<String>
  ]),
  multiple: propTypes.bool.def(false),
  selectAnyLevel: propTypes.bool.def(false)
})

const regionProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: false,
  multiple: props.multiple,
  checkStrictly: props.selectAnyLevel ? true : undefined
}

/** 选中的区域编码 */
const selectRegionCode = computed({
  get: () => {
    return Number(props.modelValue)
  },
  set: (val: number | number[] | string | string[]) => {
    emit('update:modelValue', Number(val))
  }
})

/** 区域选择 */
const emit = defineEmits(['update:modelValue', 'change'])

const onRegionChange = (val: any) => {
  emit('change', val)
}

/** 初始化 **/
const regionTree = ref<any>([])
const regionLoading = ref(true)
onMounted(() => {
  regionLoading.value = true
  getRegionTree()
    .then((data) => {
      //console.log('response: ' + JSON.stringify(data))
      for (let item of data) {
        if (item.id != 520000) {
          // 暂时只支持贵州省
          continue
        }
        regionTree.value.push(item)
      }
      regionLoading.value = false
    })
    .catch(() => {
      regionLoading.value = false
    })
})
</script>
